package com.app.controller;

import com.app.utils.JsonUtil;
import com.app.utils.Result;
import com.app.utils.WebUtils;
import com.core.aspect.Log;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@RequestMapping("/error")
public class ErrorController {

	private static String argEx[] = {"ClientAbortException"};
	private static String uriEx[] = {"login.do"};
	
	@Log("错误跳转")
	@RequestMapping(value = "/{param}.htm")
	public String login(@PathVariable String param, HttpServletRequest request, HttpServletResponse response) {
		if("404".equalsIgnoreCase(param)) {
			return "/error/404";
		}else if("500".equalsIgnoreCase(param)) {
			return "/error/500";
		}else{
			return "/error/404";
		}
	}

	/**
	 * 全局异常捕捉处理
	 *
	 * @param ex
	 * @return
	 */
	@Log("发生错误")
	@ExceptionHandler(value = Exception.class)
	public ModelAndView errorHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		ex.printStackTrace();
		//获取请求的uri
		String uri = request.getRequestURI();
		if (isIgnoreException(uri)) {
			throw new RuntimeException();
		}
		if (isIgnoreException(ex)) {
			throw new RuntimeException();
		}
		if (ex instanceof UnauthenticatedException || ex instanceof UnauthorizedException) {
			if (WebUtils.isAjaxRequest(request)) {
				WebUtils.responseJson(response, Result.returnError("权限不足 "));
				return null;
			}else {
				return new ModelAndView("/error/401");
			}
		}
		if(WebUtils.isAjaxRequest(request)){
			WebUtils.responseJson(response,JsonUtil.formatToStr(Result.returnError(ex.getMessage())));
			return null;
		}
		return new ModelAndView("/error/404");
	}



	private boolean isIgnoreException(String uri) {
		for (String name : uriEx) {
			if (name.equals(uri)) {
				return true;
			}
		}
		return false;
	}

	private boolean isIgnoreException(Exception e) {
		for (String name : argEx) {
			if (name.equals(e.getClass().getSimpleName())) {
				return true;
			}
		}
		return false;
	}

	
}
